package middleware

import (
	"XiangMu/models"
	"XiangMu/utils"
	"github.com/gin-gonic/gin"
)

func LoginFilter() gin.HandlerFunc {
	return func(c *gin.Context) {
		//check if user
		auth := c.GetHeader("Authorization")
		result, _ := models.RDB.Get(c, auth).Result()
		if result != "" {
			c.Abort()
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "登录过期",
			})

			return
		}

		userClaim, err := utils.AnalyseToken(auth)
		if err != nil {
			c.Abort()
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "请登录",
			})
			return
		}
		if userClaim == nil {
			c.Abort()
			c.JSON(401, gin.H{
				"code": 401,
				"msg":  "请登录",
			})
			return
		}
		c.Set("user", userClaim)
		c.Set("id", userClaim.Id)
		c.Set("Auth", userClaim.Auth)
		c.Next()
	}
}
